package cn.edu.buu.hospital.web;

import cn.edu.buu.hospital.entity.Doctor;
import cn.edu.buu.hospital.service.DoctorService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 医生登录控制器
 */
@Controller
public class DoctorLoginController {
    
    @Autowired
    private DoctorService doctorService;
    
    /**
     * 去往医生登录页面
     */
    @GetMapping("/toDoctorLogin")
    public String toDoctorLogin() {
        return "backend/doctorLogin";
    }
    
    /**
     * 医生登录验证
     */
    @PostMapping("/doctorLogin")
    public String doctorLogin(@RequestParam("doctorName") String doctorName,
                             @RequestParam("idCard") String idCard,
                             HttpSession session) {
        // 调用医生登录验证服务
        Doctor loginDoctor = doctorService.doctorLogin(doctorName, idCard);
        
        if (loginDoctor == null) {
            // 登录失败，重定向到医生登录页面并显示错误信息
            return "redirect:toDoctorLogin?flag=-1";
        }
        
        // 登录成功，将医生信息存入session
        session.setAttribute("loginDoctor", loginDoctor);
        
        // 重定向到医生工作台
        return "redirect:/doctor/workspace";
    }
    
    /**
     * 医生登出
     */
    @GetMapping("/doctorLogout")
    public String doctorLogout(HttpSession session) {
        // 移除医生登录信息
        session.removeAttribute("loginDoctor");
        // 如果没有其他登录信息，可以使整个会话失效
        // session.invalidate();
        return "redirect:toDoctorLogin";
    }
}